using System;
using System.IO;
using System.Reflection;
using Elevation.AdminPanel.Properties;
using Elevation.AdminPanel.Views;
using Elevation.Common.Services;
using log4net;

namespace Elevation.AdminPanel.Presenters.Impl
{
	internal class MainPresenter : IMainPresenter
	{
		#region Fields

		private static readonly ILog log = LogManager.GetLogger(typeof(MainPresenter));
		private readonly IMainView view;
		private string registrator;

		#endregion Fields

		#region Properties

		private string Registrator
		{
			get
			{
				if (string.IsNullOrEmpty(registrator))
				{
					var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;
					registrator = Path.Combine(directoryName, Resources.RunnerExe);
				}

				return registrator;
			}
		}

		#endregion Properties

		#region Constructors

		public MainPresenter(IMainView view)
		{
			this.view = view;
		}

		#endregion Constructors

		#region IMainPresenter implementation

		public void OnLoad()
		{
			if (UserService.IsAdmin())
			{
				view.DisableAdminControls();
			}
			view.Target = Registrator;
		}

		public void OnBrowse()
		{
			var target = view.BrowseForTarget();
			if (!string.IsNullOrEmpty(target))
			{
				view.Target = target;
			}
		}

		public void OnStartProcess(string adminUsername, string adminPassword)
		{
			try
			{
				log.Info("Starting runner");

				var command = string.Format("\"{0}\"", view.Target);
				StartProcess(command, adminUsername, adminPassword);

				log.Info("Runner was started");
			}
			catch (Exception e)
			{
				log.Error(e);
				view.ShowErrorMessage(e.Message);
			}
		}

		#endregion IMainPresenter implementation

		#region Helpers

		private static void StartProcess(string command, string adminUsername, string adminPassword)
		{
			var isAdmin = UserService.IsAdmin();
			if (isAdmin)
			{
				log.Info("Current user is administrator");
				log.InfoFormat("Starting command {0}", command);
				ProcessService.StartProcess(command);
			}
			else
			{
				log.Info("Current user is not administrator");

				var upnName = GetUpnUsername(adminUsername);
				log.InfoFormat("Starting command {0} with credentials {1}/{2}", command, upnName, adminPassword);
				ProcessService.StartProcess(command, upnName, adminPassword);
			}
		}

		private static string GetUpnUsername(string username)
		{
			if (username.Contains("@"))
			{
				return username;
			}
			if (username.Contains("\\"))
			{
				var components = username.Split('\\');
				var upnName = string.Format("{0}@{1}", components[1], components[0]);

				return upnName;
			}

			return username;
		}

		#endregion Helpers
	}
}